'''
Created on 2011-12-10

@author: jiangxd
'''
from Tkinter import *
from ttk import *
import os.path
import codecs
from translate.bing import *
import views

class TransView:
	def __init__(self, master):

		self.installdir = "."

		self.load_lans()
		self.translator = Translator()
		
	def load_lans(self):
		f = open(os.path.join(self.installdir,"lans"),"r")
		self.lans = {}
		for l in f.readlines():
			long,short = l.strip().split('=')
			self.lans[long] = short
		f.close()
		
	def init_widgets(self, frame):
		self.frame = frame
		self.frame.bind("<FocusIn>", self.on_focus,add=True)

		self.from_txt = Text(frame, name="trans-fromtxt",height=16)
		self.from_txt.bind("<Key>",self.on_press,add=True)
		self.from_txt.pack(side=TOP)
		self.from_txt.focus_set()


		self.bar = Frame(frame,name="trans-bar")
		self.bar.pack(side=TOP)
		
		self.from_option,self.from_lan = self.create_option(self.bar,'English')
		self.from_option.pack(side=LEFT)

		self.swap_btn = Button(self.bar,text="<=> (Ctrl + .)",command=self.on_swap)
		self.swap_btn.pack(side=LEFT)
		self.to_option,self.to_lan = self.create_option(self.bar,'ChineseSi')
		self.to_option.pack(side=LEFT)
		
		self.trans_btn = Button(self.bar,text="Translate (Ctrl + S)",command=self.on_translate)
		self.trans_btn.pack(side=LEFT)
		
		self.to_txt = Text(frame,name="trans-totxt",height=16)
		self.to_txt.pack(side=TOP)

	def create_option(self,frame,value):
		keys = self.lans.keys()
		keys.sort()

		var = StringVar(frame)
		menu = OptionMenu(frame, var, *keys)
		var.set(value)
		return menu,var
	
	def on_swap(self):
		lan = self.from_lan.get()
		self.from_lan.set(self.to_lan.get())
		self.to_lan.set(lan)
		
	def on_translate(self):
		text = self.from_txt.get(1.0, END).strip()
		if len(text) == 0:
			return
		text = text.encode('utf-8')

#		self.from_txt.focus_force()		
		self.from_txt.focus_set()
		self.from_txt.tag_add(SEL, "1.0", END)
		
		self.to_txt.delete(1.0,END)
		from_lan = self.from_lan.get()
		to_lan = self.to_lan.get()
#		print "%s->%s %s->%s" % ( from_lan,to_lan,self.lans[from_lan],self.lans[to_lan])
		totext = self.translator.translate(self.lans[from_lan], self.lans[to_lan],text)
		self.to_txt.insert(1.0,totext)
#		self.status == 'translate'
	
	def on_press(self,event):
		if event.keysym == 's' and self.lastkey != None and (self.lastkey.startswith("Alt") or self.lastkey.startswith("Control")):
			self.on_translate()
		if event.keysym == 'period' and self.lastkey != None and (self.lastkey.startswith("Alt") or self.lastkey.startswith("Control")):
			self.on_swap()
		self.lastkey = event.keysym

	def on_focus(self,event,*args):
#		self.frame.focus_set()
#		self.from_txt.focus_force()
		self.from_txt.focus_set()
#		print 'on_cocus trans'
